<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class FactoryController extends Controller
{
    public function index(Request $request)
    {
        $data = DB::table('a_factory')->orderBy('sort','desc')->get();
        return view('admin.factory.index',compact('data'));
    }

    //常见问题 添加、修改
    public function edit(Request $request)
    {
        $id = $request->input('id');
        if(!$id){   //添加
            if ($request->isMethod('POST')) {
                $post_data = $request->only(['name']);
                //插入数据    insert 返回true 或 false
                $post_data['sort'] = time();
                $result = DB::table('a_factory')->insertGetId($post_data);
                return intval($result);
            } else {
                return view('admin.factory.edit');
            }
        }
        $result = DB::table('a_factory')->where('id', $id)->update(['name'=>$request->name,'sort'=>time()]);
        return (int)$result;
    }

    //常见问题 删除
    public function del(Request $request)
    {

        $id = $request->input('id');
        $info = DB::table('a_factory')->find($id);
        if(DB::table('a_sample_info')->where('manufacturer',$info->name)->exists()){
            return '该生产厂家下有工器具无法删除！';
        }
        $result = DB::table('a_factory')->where('id', $id)->delete();
        return intval($result);
    }
}
